package com.zadtek.shopmall.activities;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.zadtek.shopmall.Event.EventChooseAddress;
import com.zadtek.shopmall.Event.EventPoiAddress;
import com.zadtek.shopmall.R;
import com.zadtek.shopmall.adapter.MyAdapter;
import com.zadtek.shopmall.base.AbsActivity;
import com.zadtek.shopmall.bean.BuyTypeItem;
import com.zadtek.shopmall.bean.OperateResponseBean2;
import com.zadtek.shopmall.bean.OperateResponseBean3;
import com.zadtek.shopmall.bean.TaskItem2;
import com.zadtek.shopmall.net.BaseObserver;
import com.zadtek.shopmall.net.BaseResponse;
import com.zadtek.shopmall.net.NetTool;
import com.zadtek.shopmall.utils.ToastUtil;
import com.zadtek.shopmall.view.NoScrollView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class SubmitTaskActivity extends AbsActivity implements View.OnClickListener {
    private View hybuy;
    private View hysendqu;
    private LinearLayout fahaddrlayt;
    private ImageView fromicon;
    private EditText gbuyaddr;
    private LinearLayout faaddlay;
    private TextView fahaddr;
    private TextView fashname;
    private LinearLayout sendaddrlayt;
    private EditText sendaddr;
    private LinearLayout sendaddlay;
    private TextView sedshaddr;
    private TextView sendshname;
    private TextView timename;
    private TextView huowutime;
    private LinearLayout beizlay;
    private EditText beizhu;
    private View beizview;
    private TextView peisfmsg;
    private TextView peisf;
    private TextView hongbao;
    private TextView xiaofeivar;
    private TextView xiaofei;
    private SeekBar seekxfid;
    private ImageView agreenxy;
    private TextView xyname;
    private TextView psfzj;
    private TextView fkprice;
    private TextView youhprice;
    private TextView syhybuy;
    private Button ordbut;
    private ImageView icBack;
    private TextView topTitle,wupin;
    private EditText etProductName,etExpiredPrice;
    private NoScrollView type_gridview;
    private EditText buysp,beizqs;

    public final static int TASK_BUY = 1;
    public final static int TASK_FETCH = 2;
    public final static int TASK_DELIVERY = 3;
    public final static String Type = "type";
    public final static String Id = "id";
    public int nowType;
    private int tip = 0;
    private int shipping = 9;
    private int id;
    private long time = 0;
    private MyAdapter adapter;
    private ArrayList<TaskItem2> buyTypeList= new ArrayList<>();
    private ArrayList<TaskItem2> fetchTypeList= new ArrayList<>();
    private ArrayList<TaskItem2> deliveryTypeList= new ArrayList<>();

    private void initView() {
        icBack = findViewById(R.id.ic_back);
        icBack.setVisibility(View.VISIBLE);
        topTitle = findViewById(R.id.title);
        topTitle.setText("帮你送");
        hybuy = (View)findViewById( R.id.hybuy );
        hysendqu = (View)findViewById( R.id.hysendqu );
        fahaddrlayt = (LinearLayout)findViewById( R.id.fahaddrlayt );
        fromicon = (ImageView)findViewById( R.id.fromicon );
        gbuyaddr = (EditText) findViewById( R.id.gbuyaddr );
        faaddlay = (LinearLayout)findViewById( R.id.faaddlay );
        fahaddr = (TextView)findViewById( R.id.fahaddr );
        fashname = (TextView)findViewById( R.id.fashname );
        sendaddrlayt = (LinearLayout)findViewById( R.id.sendaddrlayt );
        sendaddr = (EditText)findViewById( R.id.sendaddr );
        sendaddlay = (LinearLayout)findViewById( R.id.sendaddlay );
        sedshaddr = (TextView)findViewById( R.id.sedshaddr );
        sendshname = (TextView)findViewById( R.id.sendshname );
        timename = (TextView)findViewById( R.id.timename );
        huowutime = (TextView)findViewById( R.id.huowutime );
        beizlay = (LinearLayout)findViewById( R.id.beizlay );
        beizhu = (EditText)findViewById( R.id.beizhu );
        beizview = (View)findViewById( R.id.beizview );
        peisfmsg = (TextView)findViewById( R.id.peisfmsg );
        peisf = (TextView)findViewById( R.id.peisf );
        hongbao = (TextView)findViewById( R.id.hongbao );
        xiaofeivar = (TextView)findViewById( R.id.xiaofeivar );
        xiaofei = (TextView)findViewById( R.id.xiaofei );
        seekxfid = (SeekBar)findViewById( R.id.seekxfid );
        agreenxy = (ImageView)findViewById( R.id.agreenxy );
        xyname = (TextView)findViewById( R.id.xyname );
        psfzj = (TextView)findViewById( R.id.psfzj );
        fkprice = (TextView)findViewById( R.id.fkprice );
        youhprice = (TextView)findViewById( R.id.youhprice );
        syhybuy = (TextView)findViewById( R.id.syhybuy );
        ordbut = (Button)findViewById( R.id.ordbut );
        etProductName = findViewById(R.id.buysp);
        etExpiredPrice = findViewById(R.id.yuqprice);
        beizqs = findViewById(R.id.beizqs);
        type_gridview = findViewById(R.id.type_gridview);
        buysp = findViewById(R.id.buysp);
        wupin = findViewById(R.id.wupin);
        ordbut.setOnClickListener(this);
        icBack.setOnClickListener(this);
        wupin.setOnClickListener(this);
        gbuyaddr.setOnClickListener(this);
        sendaddr.setOnClickListener(this);
        huowutime.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ordbut:
                submit();
                break;
            case R.id.ic_back:
                finish();
                break;
            case R.id.wupin:
                showPicker();
                break;
            case R.id.gbuyaddr:
                startActivity(new Intent(this,ChooseAddressActivity.class).putExtra("from",EventChooseAddress.TaskFromAddress));
                break;
            case R.id.sendaddr:
                startActivity(new Intent(this,ChooseAddressActivity.class).putExtra("from",EventChooseAddress.TaskToAddress));
                break;
            case R.id.huowutime:
                showTimePicker();
                break;
        }
    }

    private void showTimePicker() {
        TimePickerView pvTime = new TimePickerBuilder(mActivity, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                Toast.makeText(mActivity, String.valueOf(date.getTime()), Toast.LENGTH_SHORT).show();
                time = date.getTime();
                huowutime.setText(getTime(date));
            }
        }).setType(new boolean[]{false, false, true, true, true, false})
                .setLabel("年", "月", "日", "时", "分", "秒")
                .build();
        pvTime.show();
    }

    private void submit() {
        Observable<BaseResponse<OperateResponseBean3>> obderver = null;
        String sendAddress = sendaddr.getText().toString();
        String buyAddress = gbuyaddr.getText().toString();
        String remark = beizhu.getText().toString();


        Map<String, Object> param = NetTool.newParams();
        param.put("buy_address",buyAddress);
        param.put("receive_address",sendAddress);
        param.put("delivery_time",time);
        param.put("shipping_fee",9);
        param.put("remark",remark);
        param.put("tip",tip);
        param.put("order_time",System.currentTimeMillis());
        switch (nowType){
            case TASK_BUY:
                String expectPrice = etExpiredPrice.getText().toString();
                String productName = etProductName.getText().toString();
                if(TextUtils.isEmpty(expectPrice)){
                    ToastUtil.showToast("请输入你的预期价格！");
                    return;
                }
                if(TextUtils.isEmpty(productName)){
                    ToastUtil.showToast("请输入需要购买的商品名字！");
                    return;
                }
                if(TextUtils.isEmpty(sendAddress)){
                    ToastUtil.showToast("请输入你的收货地址！");
                    return;
                }
                param.put("expect_price",expectPrice);
                param.put("product_name",productName);
                obderver = NetTool.getApi().submitTask(param)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
                break;
            case TASK_DELIVERY:
                String tip1 = beizqs.getText().toString();
                String productName2 = wupin.getText().toString();
                if(TextUtils.isEmpty(productName2)){
                    ToastUtil.showToast("请选择物品信息！");
                    return;
                }
                if(TextUtils.isEmpty(buyAddress)){
                    ToastUtil.showToast("请输入取货地址！");
                    return;
                }
                if(TextUtils.isEmpty(sendAddress)){
                    ToastUtil.showToast("请输入你的收货地址！");
                    return;
                }
                param.put("to_say",tip1);
                param.put("product_name",productName2);
                obderver = NetTool.getApi().submitTask3(param)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
                break;
            case TASK_FETCH:
                String tip2 = beizqs.getText().toString();
                String productName3 = wupin.getText().toString();
                if(TextUtils.isEmpty(productName3)){
                    ToastUtil.showToast("请选择物品信息！");
                    return;
                }
                if(TextUtils.isEmpty(sendAddress)){
                    ToastUtil.showToast("请输入你的收货地址！");
                    return;
                }
                if(TextUtils.isEmpty(buyAddress)){
                    ToastUtil.showToast("请输入取货地址！");
                    return;
                }
                param.put("to_say",tip2);
                param.put("product_name",productName3);
                obderver = NetTool.getApi().submitTask2(param)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
                break;
        }
        obderver.subscribe(new BaseObserver<BaseResponse<OperateResponseBean3>>(this) {
            @Override
            public void onData(BaseResponse<OperateResponseBean3> value) {
                        if(value.getCode() == 0 && value.getData()!=null){
                            if(value.getData().isSuccess()){
                                ToastUtil.showToast("提交成功!");
                                finish();
                            }else{
                                ToastUtil.showToast("操作失败!"+value.getData().getMessage());
                            }
                        }
                    }});
    }

    @Override
    public int setView() {
        return R.layout.activity_submit_task;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        nowType = getIntent().getIntExtra(Type,1);
        id = getIntent().getIntExtra(Id,-1);
        initView();
        initLogic();
        requestData();
    }

    private void requestData() {
        switch (nowType){
            case TASK_BUY:
                requestInfo();
                break;
            case TASK_DELIVERY:
                requestDeliveryInfo();
                break;
            case TASK_FETCH:
                requestFetchInfo();
                break;
        }
    }

    private void requestFetchInfo() {
        NetTool.getApi().fetch(String.valueOf(id))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new BaseObserver<BaseResponse<List<TaskItem2>>>(this) {
                    @Override
                    public void onData(BaseResponse<List<TaskItem2>> value) {
                        if(value.getCode()==0 && value.getData()!=null){
                            if(value.getData().size()!=0){
                                fetchTypeList.addAll(value.getData());
                            }
                        }
                    }
                });
    }

    private void requestDeliveryInfo() {
        NetTool.getApi().delivery(String.valueOf(id))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new BaseObserver<BaseResponse<List<TaskItem2>>>(this) {
                    @Override
                    public void onData(BaseResponse<List<TaskItem2>> value) {
                        if(value.getCode()==0 && value.getData()!=null){
                            if(value.getData().size()!=0){
                                deliveryTypeList.addAll(value.getData());
                            }
                        }
                    }
                });
    }

    private void requestInfo() {
        NetTool.getApi().buy(String.valueOf(id))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new BaseObserver<BaseResponse<List<TaskItem2>>>() {
                    @Override
                    public void onData(BaseResponse<List<TaskItem2>> value) {
                        if(value.getCode()==0 && value.getData()!=null){
                            if(value.getData().size()!=0){
                                type_gridview.setVisibility(View.VISIBLE);
                                buyTypeList.addAll(value.getData());
                                adapter.notifyDataSetChanged();
                            }
                        }
                    }
                });
    }

    private void initLogic() {
        seekxfid.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tip  = progress/2;
                if(tip!=0){
                    xiaofeivar.setText(tip+"元");
                    psfzj.setText("配送费+小费：");
                    fkprice.setText("￥"+(tip+shipping));
                }else{
                    xiaofeivar.setText("￥0");
                    psfzj.setText("配送费：￥");
                    fkprice.setText("￥"+(tip+shipping));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        switch (nowType){
            case TASK_BUY:
                topTitle.setText("帮你买");
                hybuy.setVisibility(View.VISIBLE);
                hysendqu.setVisibility(View.GONE);
                timename.setText("送达时间");
                huowutime.setText("立即送达");
                gbuyaddr.setHint("请输入购买地址(选填)");
                initAdapter();
                break;
            case TASK_FETCH:
                topTitle.setText("帮你取");
                hybuy.setVisibility(View.GONE);
                hysendqu.setVisibility(View.VISIBLE);
                timename.setText("配送时间");
                huowutime.setText("立即送达");
                gbuyaddr.setHint("请输入取货地址(必填)");
                break;
            case TASK_DELIVERY:
                topTitle.setText("帮你送");
                hybuy.setVisibility(View.GONE);
                hysendqu.setVisibility(View.VISIBLE);
                timename.setText("取件时间");
                huowutime.setText("立即取件");
                gbuyaddr.setHint("请输入发货地址(必填)");
                break;
        }

    }

    private void initAdapter() {
        adapter = new MyAdapter<TaskItem2>(buyTypeList,R.layout.buy_type_item) {
            @Override
            public void bindView(final ViewHolder holder, TaskItem2 obj) {
                holder.setText(R.id.wuptype,obj.getTitle());
                if(obj.isChoose()){
                    Drawable drawable = getResources().getDrawable(R.drawable.syg_byradiusel);
                    holder.getItemView().setBackground(drawable);
                }else{
                    Drawable drawable = getResources().getDrawable(R.drawable.syg_byradius);
                    holder.getItemView().setBackground(drawable);
                }
                holder.setOnClickListener(R.id.wuptype, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TaskItem2 item2 = buyTypeList.get(holder.getItemPosition());
                        item2.setChoose(!item2.isChoose());
                        updateChoose();
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        };
        type_gridview.setAdapter(adapter);
    }

    private void updateChoose() {
        StringBuilder builder = new StringBuilder();
        for(TaskItem2 item2:buyTypeList){
            if(item2.isChoose()){
                builder.append(item2.getTitle());
                builder.append(",");
            }
        }
        buysp.setText(builder.toString());
    }

    private void showPicker(){
        final List<String> op1 = new ArrayList<>();
        if(nowType == TASK_FETCH){
            for(TaskItem2 item2:fetchTypeList){
                op1.add(item2.getTitle());
            }
        }else{
            for(TaskItem2 item2:deliveryTypeList){
                op1.add(item2.getTitle());
            }
        }
        final List<String> op2 = new ArrayList<>();
        final List<String> op3 = new ArrayList<>();

        OptionsPickerView pvOptions = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = op1.get(options1);
                String tx2 = op2.get(options1);
                String tx3 = op3.get(options1);
                ToastUtil.showToast(tx +","+tx2+","+tx3);
                wupin.setText(tx +","+tx2+","+tx3);
            }
        }).setTitleText("物品信息")
                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x00000000) //设置外部遮罩颜色
                .build();
        op2.add("1kg");
        op2.add("2kg");
        op2.add("3kg");
        op2.add("4kg");
        op3.add("100元以下");
        op3.add("200元以下");
        op3.add("300元以下");
        op3.add("400元以下");
        pvOptions.setNPicker(op1,op2,op3);
        pvOptions.show();
    }

    @Subscribe
    public void onEventMainThread(EventChooseAddress event) {
        if(event.getAddressItem()!=null){
            if(event.getFrom() == EventChooseAddress.TaskFromAddress){
                gbuyaddr.setText(event.getAddressItem().getAddressDetail());
            }else if(event.getFrom() == EventChooseAddress.TaskToAddress){
                sendaddr.setText(event.getAddressItem().getAddressDetail());
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm");
        return format.format(date);
    }
}
